package co.recloud.ariadne.model.plan;

import java.util.Map;
import java.util.Set;

import co.recloud.ariadne.model.logical.Column;
import co.recloud.ariadne.model.logical.Condition;
import co.recloud.ariadne.model.logical.Table;
import co.recloud.ariadne.model.logical.Transaction;
import co.recloud.ariadne.persistor.KeyValuePersistor;
import co.recloud.ariadne.persistor.KeyValuePersistorImpl;

public class Select extends Operator {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3489808587808826754L;

	public Select(Transaction transaction) {
		super(transaction);
		// TODO Auto-generated constructor stub
	}

	private Condition condition;

	/**
	 * @param condition the condition to set
	 */
	public void setCondition(Condition condition) {
		this.condition = condition;
	}

	/**
	 * @return the condition
	 */
	public Condition getCondition() {
		return condition;
	}
	
	public void execute(String localhost, int port) {
		this.getChildren().get(0).execute(localhost, port);
		KeyValuePersistor kv = new KeyValuePersistorImpl(this.getTransaction());
		Table childTable = this.getChildren().get(0).getTable();
		Set<String> keys = kv.getAllKeys(childTable);
		for(String key : keys) {
			String rowValue = kv.getValue(key, new Column(childTable, condition.getLeftColumn().getField()));
			if(rowValue.equals(condition.getRightValue())) {
				Map<String, Object> columnMap = kv.getAllColumns(key, childTable);
				for(String columnString : columnMap.keySet()) {
					Column column = Column.parseColumn(columnString, childTable, this.getTableAliases());
					kv.setValue(key, new Column(this.getTable(), column.toString()), (String) columnMap.get(columnString));
				}
			}
		}
		if(childTable.isResultSet()) {
			kv.dropTable(childTable);
		}
	}
}
